// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
const isProduction = process.env.NODE_ENV !== 'development';
const devNeedCdn = true;
const TimeStamp = new Date().getTime();
const cdnUrl = `http://down.dd0519.cn//cdn/`;
const cdn = {
  externals: {
    vue: 'Vue',
    vuex: 'Vuex',
    'vue-router': 'VueRouter',
  },
  css: [cdnUrl + 'vant@2.5.min.css'],
  js: [
    cdnUrl + 'vue@2.6.11.min.js',
    cdnUrl + 'vuex@3.1.1.min.js',
    cdnUrl + 'vue-router@3.0.0.min.js',
    cdnUrl + 'vant@2.5.min.js',
    cdnUrl + 'axios.min.js',
  ],
};

module.exports = {
  lintOnSave: false,
  outputDir: 'vue-example/dist',
  publicPath: '/',
  assetsDir: 'static',
  productionSourceMap: false,
  runtimeCompiler: true,
  devServer: {
    open: false, // 自动启动浏览器
    host: '0.0.0.0', // localhost
    port: 8088, //端口
    hotOnly: false, // 热更新
    // 关闭主机检查，使微应用可以被 fetch
    disableHostCheck: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
  chainWebpack: (config) => {
    config.entry('main').add('babel-polyfill');
    // 图片压缩--开始
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({ bypassOnDebug: true })
      .end();
    // 图片压缩--结束
    config.plugin('html').tap((args) => {
      if (isProduction || devNeedCdn) args[0].cdn = cdn;
      return args;
    });
    /* 添加分析工具*/
    if (process.env.NODE_ENV === 'production') {
      if (process.env.npm_config_report) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
          .end();
        // config.plugins.delete('prefetch');
      }
    }
  },
  configureWebpack: (config) => {
    if (isProduction || devNeedCdn) config.externals = cdn.externals;
    if (isProduction) {
      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              warnings: false,
              drop_debugger: true,
              drop_console: true,
              pure_funcs: ['console.log'],
            },
          },
          sourceMap: false,
          parallel: true,
        })
      );
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240, // 超过10k进行压缩
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false, // 删除原文件
        })
      );
      config.output.filename = `static/js/[name].${TimeStamp}.js`;
      config.output.chunkFilename = `static/js/[name].${TimeStamp}.js`;
      config.optimization = {
        splitChunks: {
          chunks: 'all', //async异步代码分割 initial同步代码分割 all同步异步分割都开启
          minSize: 20000, //字节 引入的文件大于20kb才进行分割
          maxSize: 200000, //40kb，尝试将大于40kb的文件拆分成n个40kb的文件
          minChunks: 1, //模块至少使用次数
          maxAsyncRequests: 5, //同时加载的模块数量最多是5个，只分割出同时引入的前5个文件
          maxInitialRequests: 3, //首页加载的时候引入的文件最多3个
          automaticNameDelimiter: '-', //缓存组和生成文件名称之间的连接符
          name: true, //缓存组里面的filename生效，覆盖默认命名
          cacheGroups: {
            //缓存组，将所有加载模块放在缓存里面一起分割打包
            vendor: {
              test: /[\\/]node_modules[\\/]_?vant(.*)/,
              priority: -10, //优先级，先打包到哪个组里面，值越大，优先级越高
              filename: 'vendors.js',
            },
            default: {
              priority: -20,
              reuseExistingChunk: true, //模块嵌套引入时，判断是否复用已经被打包的模块
              filename: 'common.js',
            },
          },
        },
      };
    }
  },
};
